package com.jkl.service.home;

import com.jkl.dao.home.MainIndexMapper;
import com.jkl.dao.home.SourceClassificationMapper;
import com.jkl.entity.home.HomeMappingEntity;
import com.jkl.entity.home.HomeRequestEntity;
import com.jkl.entity.home.HomeSourceMappingEntity;
import com.jkl.entity.home.SourceResponseEnetity;
import com.jkl.service.home.sourceCassificationInter.SourceCassificationService;
import com.jkl.untils.DateUtil;
import com.jkl.untils.GetIntUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zjj
 * @date  2019/9/2 15:44
 * @Description  ${描述一个类的相关信息}
 */
@Service
public class SourceCassificationServiceImpl implements SourceCassificationService {
    @Autowired
    private SourceClassificationMapper sourceClassificationDao;

    @Autowired
    private MainIndexMapper mainIndexMapperDao;

    @Override
    public SourceResponseEnetity getCoverageTrend(HomeRequestEntity homeRequestEntity) {
        String startTime = LocalDate.now().minusYears(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
        String endTime = LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));

        homeRequestEntity.setStartTime(startTime);
        homeRequestEntity.setEndTime(endTime);
        List<HomeSourceMappingEntity> homeSourceMappingEntities = sourceClassificationDao.coverageRate(homeRequestEntity);
        //获取最近一年月份列表
        List<String> montListByTime = DateUtil.getMontListByTime(startTime, endTime);
        List<Map<String, Object>> monthlistMap = new ArrayList<>();
        for (int i = 0; i < montListByTime.size(); i++) {
            Map mapTime = new HashMap();
            mapTime.put(DateUtil.formatToView(montListByTime.get(i)), 0);
            monthlistMap.add(mapTime);
        }
        List<Integer> coverageTotal = new ArrayList<>();
        List<String> yearArray = new ArrayList<>();
        for (Map<String, Object> map : monthlistMap) {
            String key = map.keySet().iterator().next();
            //总主体数
            Integer totaCount = total(key, homeRequestEntity.getAreaCode());
            for (HomeSourceMappingEntity homeSourceMappingEntity : homeSourceMappingEntities) {
                String time = DateUtil.formatToView(homeSourceMappingEntity.getYEAR());
                if (time.equals(key)) {
                    int  total=0;
                    //计算总覆盖率
                    if (totaCount!=0) {
                        total= new BigDecimal(homeSourceMappingEntity.getTotalStart()).divide(new BigDecimal(totaCount), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
                    }
                    map.put(key, total);
                    break;
                }
            }
            coverageTotal.add(Integer.parseInt(map.get(key).toString()));
            yearArray.add(key);
        }
        SourceResponseEnetity sourceResponseEnetity = new SourceResponseEnetity();
        sourceResponseEnetity.setCoverageTotalArray(coverageTotal);
        sourceResponseEnetity.setYearArray(yearArray);
        return sourceResponseEnetity;
    }
    /**
     *@参数
     *@返回值
     * 处理跨年取年指标
     */
    private Integer total(String key,String areaCode) {
        HomeRequestEntity homeRequestEntity = new HomeRequestEntity();
        //截取年份
        String substring = key.substring(0, 4);
        //设置年指标查询条件
        homeRequestEntity.setTime(substring);
        homeRequestEntity.setAreaCode(areaCode);
        HomeMappingEntity yearIndex = mainIndexMapperDao.getYearIndex(homeRequestEntity);
        if (yearIndex != null) {
            return yearIndex.getTotalCount()!=null?yearIndex.getTotalCount():0;
        }else {
            String year = LocalDate.of(Integer.parseInt(substring), 1, 1).minusYears(1).format(DateTimeFormatter.ofPattern("yyyy"));
            homeRequestEntity.setTime(year);
            yearIndex = mainIndexMapperDao.getYearIndex(homeRequestEntity);
            if (yearIndex == null) {
                return 0;
            } else {
                return yearIndex.getTotalCount()!=null?yearIndex.getTotalCount():0;
            }
        }
    }
    @Override
    public SourceResponseEnetity getCoverageSituation(HomeRequestEntity homeRequestEntity) {
        HomeSourceMappingEntity coverageSituation = sourceClassificationDao.getCoverageSituation(homeRequestEntity);
        int communituRate=0;
        int companyRate =0;
        int institutionalUnitRate =0;
        //小区覆盖率
        if (coverageSituation.getCommunityCount()!=null&&coverageSituation.getCommunityCount().intValue() !=0) {
            communituRate = new BigDecimal(coverageSituation.getCommunityStart()!=null?coverageSituation.getCommunityStart():0).divide(new BigDecimal(coverageSituation.getCommunityCount()), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
        }
        //企业覆盖率
        if (coverageSituation.getCompanyCount()!=null&&coverageSituation.getCompanyCount().intValue()!=0) {
            companyRate = new BigDecimal(coverageSituation.getCompanyStart()!=null?coverageSituation.getCompanyStart():0).divide(new BigDecimal(coverageSituation.getCompanyCount()), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
        }
        //公共机构覆盖率
        if (coverageSituation.getCompanyCount()!=null&&coverageSituation.getCompanyCount().intValue()!=0) {
            institutionalUnitRate = new BigDecimal(coverageSituation.getInstitutionalUnitStart()!=null?coverageSituation.getInstitutionalUnitStart():0).divide(new BigDecimal(coverageSituation.getInstitutionalUnitCount()), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
        }

        SourceResponseEnetity sourceResponseEnetity = new SourceResponseEnetity();
        sourceResponseEnetity.setCommunity(communituRate);
        sourceResponseEnetity.setCommunityStart(GetIntUtil.getInt(coverageSituation.getCommunityStart()!=null?coverageSituation.getCommunityStart():0));
        sourceResponseEnetity.setCommunityCount(GetIntUtil.getInt(coverageSituation.getCommunityCount()!=null?coverageSituation.getCommunityCount():0));
        sourceResponseEnetity.setCompany(companyRate);
        sourceResponseEnetity.setCompanyStart(GetIntUtil.getInt(coverageSituation.getCompanyStart()!=null?coverageSituation.getCompanyStart():0));
        sourceResponseEnetity.setCompanyCount(GetIntUtil.getInt(coverageSituation.getCompanyCount()!=null?coverageSituation.getCompanyCount():0));
        sourceResponseEnetity.setInstitutionalUnit(institutionalUnitRate);
        sourceResponseEnetity.setInstitutionalUnitStart(GetIntUtil.getInt(coverageSituation.getInstitutionalUnitStart()!=null?coverageSituation.getInstitutionalUnitStart():0));
        sourceResponseEnetity.setInstitutionalUnitCount(GetIntUtil.getInt(coverageSituation.getInstitutionalUnitCount()!=null?coverageSituation.getInstitutionalUnitCount():0));
        return sourceResponseEnetity;
    }

    @Override
    public List<SourceResponseEnetity> getAreaCoverageRanking(HomeRequestEntity homeRequestEntity) {
        List<SourceResponseEnetity> list = new ArrayList<>();
        List<HomeSourceMappingEntity> areaCoverageRanking = sourceClassificationDao.getAreaCoverageRanking(homeRequestEntity);
        if (areaCoverageRanking!=null) {
            for (HomeSourceMappingEntity homeSourceMappingEntity : areaCoverageRanking) {
                int communituRate = 0;
                int companyRate = 0;
                int institutionalUnitRate = 0;
                //小区覆盖率
                if (homeSourceMappingEntity.getCommunityCount()!=null&&homeSourceMappingEntity.getCommunityCount().intValue() !=0) {
                    communituRate = new BigDecimal(homeSourceMappingEntity.getCommunityStart()!=null?homeSourceMappingEntity.getCommunityStart():0).divide(new BigDecimal(homeSourceMappingEntity.getCommunityCount()), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
                }
                //企业覆盖率
                if (homeSourceMappingEntity.getCompanyCount()!=null&&homeSourceMappingEntity.getCompanyCount().intValue()!=0) {
                    companyRate = new BigDecimal(homeSourceMappingEntity.getCompanyStart()!=null?homeSourceMappingEntity.getCompanyStart():0).divide(new BigDecimal(homeSourceMappingEntity.getCompanyCount()), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
                }
                //公共机构覆盖率
                if (homeSourceMappingEntity.getInstitutionalUnitCount()!=null&&homeSourceMappingEntity.getInstitutionalUnitCount().intValue()!=0) {
                    institutionalUnitRate = new BigDecimal(homeSourceMappingEntity.getInstitutionalUnitStart()!=null?homeSourceMappingEntity.getInstitutionalUnitStart():0).divide(new BigDecimal(homeSourceMappingEntity.getInstitutionalUnitCount()), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
                }
                //综合覆盖率
                int complexCoverage = new BigDecimal(communituRate + companyRate + institutionalUnitRate).divide(new BigDecimal(3),0).intValue();
                SourceResponseEnetity sourceResponseEnetity = new SourceResponseEnetity();
                sourceResponseEnetity.setAreaName(homeSourceMappingEntity.getAreaName());
                sourceResponseEnetity.setCommunity(communituRate);
                sourceResponseEnetity.setCompany(companyRate);
                sourceResponseEnetity.setPublicInstitutions(institutionalUnitRate);
                sourceResponseEnetity.setComplexCoverage(complexCoverage);
                list.add(sourceResponseEnetity);
            }
        }
        return list;
    }
    @Override
    public SourceResponseEnetity getBuildingProgress(HomeRequestEntity homeRequestEntity) {
        HomeSourceMappingEntity buildingProgress = sourceClassificationDao.getBuildingProgress(homeRequestEntity);
        SourceResponseEnetity sourceResponseEnetity = new SourceResponseEnetity();
        sourceResponseEnetity.setDemonstrationCommunityBefore(GetIntUtil.getInt(buildingProgress.getDemonstrationCommunityBefore()!=null?buildingProgress.getDemonstrationCommunityBefore():0));
        sourceResponseEnetity.setDemonstrationCommunitystart(GetIntUtil.getInt(buildingProgress.getDemonstrationCommunitystart()!=null?buildingProgress.getDemonstrationCommunitystart():0));
        sourceResponseEnetity.setDemonstrationCommunityComplete(GetIntUtil.getInt(buildingProgress.getCommunityComplete()!=null?buildingProgress.getCommunityComplete():0));
        sourceResponseEnetity.setDemonstrationCommunityTotal(GetIntUtil.getInt(buildingProgress.getDemonstrationCommunityTotal()!=null?buildingProgress.getDemonstrationCommunityTotal():0));
        sourceResponseEnetity.setDemonstrationSliceBefore(GetIntUtil.getInt(buildingProgress.getDemonstrationSliceBefore()!=null?buildingProgress.getDemonstrationSliceBefore():0));
        sourceResponseEnetity.setDemonstrationSliceStart(GetIntUtil.getInt(buildingProgress.getDemonstrationSliceStart()!=null?buildingProgress.getDemonstrationSliceStart():0));
        sourceResponseEnetity.setDemonstrationSliceComplete(GetIntUtil.getInt(buildingProgress.getDemonstrationSliceComplete()!=null?buildingProgress.getDemonstrationSliceComplete():0));
        sourceResponseEnetity.setDemonstrationSliceTotal(GetIntUtil.getInt(buildingProgress.getDemonstrationSliceTotal()!=null?buildingProgress.getDemonstrationSliceTotal():0));
        sourceResponseEnetity.setBusinessBefore(GetIntUtil.getInt(buildingProgress.getBusinessBefore()!=null?buildingProgress.getBusinessBefore():0));
        sourceResponseEnetity.setBusinessStart(GetIntUtil.getInt(buildingProgress.getBusinessStart()!=null?buildingProgress.getBusinessStart():0));
        sourceResponseEnetity.setBusinessComplete(GetIntUtil.getInt(buildingProgress.getBusinessComplete()!=null?buildingProgress.getBusinessComplete():0));
        sourceResponseEnetity.setBusinessTotal(GetIntUtil.getInt(buildingProgress.getBusinessTotal()!=null?buildingProgress.getBusinessTotal():0));
        sourceResponseEnetity.setCommunityBefore(GetIntUtil.getInt(buildingProgress.getCommunityBefore()!=null?buildingProgress.getCommunityBefore():0));
        sourceResponseEnetity.setCommunityStartt(GetIntUtil.getInt(buildingProgress.getCommunityStartt()!=null?buildingProgress.getCommunityStartt():0));
        sourceResponseEnetity.setCommunityComplete(GetIntUtil.getInt(buildingProgress.getCommunityComplete()!=null?buildingProgress.getCommunityComplete():0));
        sourceResponseEnetity.setCommunityTotall(GetIntUtil.getInt(buildingProgress.getCommunityTotall()!=null?buildingProgress.getCommunityTotall():0));
        return sourceResponseEnetity;
    }

    @Override
    public  Map<String, Object> getTimedDemonstration(HomeRequestEntity homeRequestEntity) {
        List<HomeSourceMappingEntity> timedDemonstration = sourceClassificationDao.getTimedDemonstration(homeRequestEntity);
        List<String> community = new ArrayList<>();
        List<String> business = new ArrayList<>();
        for (int i = 0; i < timedDemonstration.size(); i++) {
            if (i == 3) {
                break;
            }
            community.add(timedDemonstration.get(i).getCommunityArea()!=null?timedDemonstration.get(i).getCommunityArea():"");
            business.add(timedDemonstration.get(i).getBusiness()!=null?timedDemonstration.get(i).getBusiness():"");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("timedDemonstrationCommunityList", community);
        map.put("timedDemonstrationBusinessList", business);
        return map;
    }

    @Override
    public  List<SourceResponseEnetity> getDemonstrationPointBuildDetain(HomeRequestEntity homeRequestEntity) {
        List<HomeSourceMappingEntity> demonstrationPointBuildDetain = sourceClassificationDao.getDemonstrationPointBuildDetain(homeRequestEntity);
        List<SourceResponseEnetity> list = new ArrayList<>();
        for (HomeSourceMappingEntity homeSourceMappingEntity : demonstrationPointBuildDetain) {
            int demonstrationCommunityRadio=0;
            int demonstrationSliceRadio=0;
            int businessRadio=0;
            int communityRadio=0;
            SourceResponseEnetity sourceResponseEnetity = new SourceResponseEnetity();
            //示范小区占比
            if (homeSourceMappingEntity.getDemonstrationCommunityCompleteAim()!=null && homeSourceMappingEntity.getDemonstrationCommunityCompleteAim().intValue()!=0) {
                demonstrationCommunityRadio = new BigDecimal(homeSourceMappingEntity.getDemonstrationCommunityComplete()!=null?homeSourceMappingEntity.getDemonstrationCommunityComplete():0).divide(new BigDecimal(homeSourceMappingEntity.getDemonstrationCommunityCompleteAim()), 2,BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
            }
            //示范片区占比
            if (homeSourceMappingEntity.getDemonstrationSliceAim()!=null && homeSourceMappingEntity.getDemonstrationSliceAim().intValue()!=0) {
                demonstrationSliceRadio = new BigDecimal(homeSourceMappingEntity.getDemonstrationSliceComplete()!=null?homeSourceMappingEntity.getDemonstrationSliceComplete():0).divide(new BigDecimal(homeSourceMappingEntity.getDemonstrationSliceAim()), 2,BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
            }
            //定时定点商业区占比
            if (homeSourceMappingEntity.getBusinessAim()!=null && homeSourceMappingEntity.getBusinessAim().intValue()!=0) {
                businessRadio = new BigDecimal(homeSourceMappingEntity.getBusinessComplete()).divide(new BigDecimal(homeSourceMappingEntity.getBusinessAim()), 2,BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
            }
            //定时定点小区占比
            if (homeSourceMappingEntity.getCommunityAim()!=null && homeSourceMappingEntity.getCommunityAim().intValue()!=0) {
                communityRadio = new BigDecimal(homeSourceMappingEntity.getCommunityComplete()).divide(new BigDecimal(homeSourceMappingEntity.getCommunityAim()), 2,BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
            }
            sourceResponseEnetity.setAreaName(homeSourceMappingEntity.getAreaName());
            sourceResponseEnetity.setDemonstrationCommunityRadio(demonstrationCommunityRadio);
            sourceResponseEnetity.setDemonstrationSliceRadio(demonstrationSliceRadio);
            sourceResponseEnetity.setBusinessRadio(businessRadio);
            sourceResponseEnetity.setCommunityRadio(communityRadio);
            list.add(sourceResponseEnetity);
        }
        return list;
    }

    @Override
    public SourceResponseEnetity getGisAnalysis(HomeRequestEntity homeRequestEntity) {
        HomeSourceMappingEntity gisAnalysis = sourceClassificationDao.getGisAnalysis(homeRequestEntity);
        int city =0;
        int country =0;
        int total =0;
        //计算设区市覆盖率
        if (gisAnalysis!=null && gisAnalysis.getCoverageCity()!=null &&gisAnalysis.getCoverageCity().intValue()!=0) {
            city = new BigDecimal(gisAnalysis.getCoverageCityCount()).divide(new BigDecimal(gisAnalysis.getCoverageCity()), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
        }
        //计算设县市覆盖率
        if (gisAnalysis!=null && gisAnalysis.getCoverageCountry()!=null &&gisAnalysis.getCoverageCountry().intValue()!=0) {
            country = new BigDecimal(gisAnalysis.getCoverageCountryCount()).divide(new BigDecimal(gisAnalysis.getCoverageCountry()), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
        }
        //总覆盖率
        if (gisAnalysis!=null && gisAnalysis.getTotalCount()!=null && gisAnalysis.getTotalCount().intValue()!=0) {
            total = new BigDecimal(gisAnalysis.getTotalStart()).divide(new BigDecimal(gisAnalysis.getTotalCount()), 2, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).intValue();
        }
        SourceResponseEnetity sourceResponseEnetity = new SourceResponseEnetity();
        sourceResponseEnetity.setCoverageCountry(country);
        sourceResponseEnetity.setCoverageCity(city);
        sourceResponseEnetity.setCoverageTotal(total);
        if (gisAnalysis!=null) {
            sourceResponseEnetity.setGarbageClassificationSubjectCount(GetIntUtil.getInt( gisAnalysis.getTotalStart()!=null?gisAnalysis.getTotalStart():0));
        }else{
            sourceResponseEnetity.setGarbageClassificationSubjectCount(0);
        }
        return sourceResponseEnetity;
    }
}
